package com.ship.control;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ship.common.SessionInfo;
import com.ship.entity.User;
import com.ship.enume.LoginMessage;
import com.ship.service.BaseService;



public class AuthorizationCredit extends BaseService{

	public final String SESSION_NAME="memberSessionInfo";

	public LoginMessage login(HttpServletRequest request,String sign,String pass){
		User user=this.dao.loadObject(User.class, "sign=?", sign);
		//用户未找到
		if(null==user){
			return LoginMessage.NOFOUND;
		}
		//密码错误
		if(!user.getPass().equals(pass)){
			return LoginMessage.ERROR;
		}
		//账号被禁用
		if(!user.getStatus()){
			return LoginMessage.LIMIT;
		}
		
		SessionInfo sessionInfo=new SessionInfo();
		sessionInfo.setUserId(user.getId());
		sessionInfo.setSign(user.getSign());
		sessionInfo.setUserType(user.getUserType());
		sessionInfo.setName(user.getName());
		request.getSession().setAttribute(SESSION_NAME, sessionInfo);
		
		return null;
	}
	
	public void loginout(HttpServletRequest request){
		request.getSession().removeAttribute(SESSION_NAME);		
		request.getSession().invalidate();	
	}
	
	
	public SessionInfo getSessionInfo(HttpServletRequest request) {

		SessionInfo sessionObj = (SessionInfo) request.getSession().getAttribute(SESSION_NAME);

		if (null == sessionObj)
			return null;
		else
			return sessionObj;
	}

	public boolean signinValidate(HttpServletRequest request) throws Exception {

		if (request.getSession().getAttribute(SESSION_NAME) != null)
			return true;
		else
			return false;
	}

	public void redirectSigninValidateFailView(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String failView = this.signinValidateFailView;
		String contextPath = request.getContextPath();

		if (!contextPath.equals("")) {
			if (!contextPath.substring(contextPath.length() - 1).equals("/")) {
				contextPath += "/";
			}
		} else {
			contextPath = "/";
		}
		failView = failView.replaceAll("~/", contextPath);

		response.sendRedirect(failView);
		
	}

	private String signinValidateFailView;
	
	public void setSigninValidateFailView(String signinValidateFailView) {
		this.signinValidateFailView = signinValidateFailView;
	}

}
